#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QFile>
#include <QDir>
#include <QFileInfo>
#include <QStringList>
#include <QMessageBox>
#include <QDebug>
#include <QVariant>
#include <QTextStream>
#include <QMap>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    this->add_index = false;

    QDir d;
    if (!d.mkpath("./index")) {
        QMessageBox::critical(this, "系统错误", "无法创建文件夹：" + d.absolutePath());
    }

    this->setWindowFlags(this->windowFlags() & ~Qt::WindowMaximizeButtonHint);
    this->setWindowIcon(QIcon(":/icon/icon.png"));

    this->index_thread = new IndexThread;
    this->search_thread = new SearchThread;
    this->show_dlg = new ShowIndexDialog(this);

    this->connect(this->show_dlg, SIGNAL(send_db_name(QString)),
                  this, SLOT(receive_db_name(QString)));
    this->connect(this->index_thread, SIGNAL(send_file_msg(int,int,QString,QString)),
                  this, SLOT(receive_file_msg(int,int,QString,QString)));
    this->connect(this->index_thread, SIGNAL(send_error(QString,QString,QString)),
                  this, SLOT(receive_error(QString,QString,QString)));
    this->connect(this->index_thread, SIGNAL(send_finished()),
                  this, SLOT(receive_index_finished()));
    this->connect(this->search_thread, SIGNAL(send_list(QVariant)),
                  this, SLOT(receive_list(QVariant)));
}

MainWindow::~MainWindow()
{
    this->index_thread->terminate();
    this->index_thread->wait(1);
    this->search_thread->terminate();
    this->search_thread->wait(1);
    delete this->index_thread;
    delete this->search_thread;
    delete this->show_dlg;
    delete ui;
}

void MainWindow::receive_file_msg(int already, int count, QString file_name, QString msg) {
    this->ui->result_text_edit->setPlainText(
                "已索引：" + QVariant(already).toString() + "/" + QVariant(count).toString() +
                "\r\n" + msg + "：" + file_name);
}

void MainWindow::receive_error(QString error_type, QString error_info, QString sql) {
    this->index_thread->terminate();
    this->index_thread->wait(1);
    QFile errfile("error.log");
    if (!errfile.open(QIODevice::WriteOnly | QIODevice::Text)) {
        QMessageBox::critical(this, "系统错误", "无法写入文件error.log");
        return;
    }
    QTextStream ts(&errfile);
    ts << error_type << endl << endl << error_info << endl << endl << sql;
    errfile.close();
    this->ui->create_index->setText("建立索引");
    this->ui->create_index->setEnabled(true);
    QMessageBox::information(this, "系统提示", "索引出错，错误类型：" + error_type);
}

void MainWindow::receive_list(QVariant v) {
    QList<Searched> list = v.value<QList<Searched>>();
    this->searched = list;
    QString text = this->ui->result_text_edit->placeholderText();
    for (Searched item : list) {
        text += item.file_name + ":" + QVariant(item.line_number).toString() +
                "\r\n" + item.code + "\r\n\r\n";
    }
    this->ui->result_text_edit->setPlainText(text);
    this->ui->search_button->setEnabled(true);
    this->ui->search_button->setText("查找");
}

void MainWindow::receive_index_finished() {
    this->ui->result_text_edit->setPlainText("");
    this->ui->create_index->setText("建立索引");
    this->ui->create_index->setEnabled(true);
    QMessageBox::information(this, "系统提示", "索引完成");
}

void MainWindow::receive_db_name(QString db_name) {
    this->ui->fold_line_edit->setText(db_name);
}

void MainWindow::on_search_button_clicked()
{
    QString index_file;
    QString index_dir = this->ui->fold_line_edit->text();
    QStringList file_list = index_dir.split(QDir::separator());
    if (file_list.last() == "") {
        file_list.pop_back();
    }
    index_file = file_list.last();
    QString db_file = "./index/" + index_file + ".db";
    QFile file(db_file);
    if (!file.exists()) {
        QMessageBox::information(this, "系统提示", "未找到索引文件，请先索引目录！");
        return;
    }

    this->ui->search_button->setEnabled(false);
    this->ui->search_button->setText("查找中");
    this->searched.clear();
    this->ui->result_text_edit->setPlainText("");

    QString search_identifier = this->ui->identifier_line_edit->text();
    this->search_thread->set_configure(db_file, search_identifier);
    this->search_thread->start();
}

void MainWindow::on_again_search_button_clicked()
{
    this->ui->result_text_edit->clear();
    QString text = this->ui->result_text_edit->toPlainText();
    for (Searched s : this->searched) {
        if (s.code.contains(this->ui->again_line_edit->text())) {
            QString line_string = QVariant(s.line_number).toString();
            text += s.file_name + ":" + line_string + "\r\n" + s.code + "\r\n\r\n";
        }
    }
    this->ui->result_text_edit->setPlainText(text);
}

void MainWindow::on_show_index_clicked()
{
    QDir dir("./index");
    QStringList name_filters;
    name_filters << "*.db";
    QStringList file_list = dir.entryList(name_filters, QDir::Files | QDir::Readable, QDir::Name);
    if (file_list.isEmpty()) {
        QMessageBox::information(this, "系统提示", "当前没有索引文件");
        return;
    }

    this->show_dlg->setFileList(file_list);
    this->show_dlg->exec();
}

void MainWindow::on_create_index_clicked()
{
    QString index_file;
    QString index_dir = this->ui->fold_line_edit->text();
    QStringList file_list = index_dir.split(QDir::separator());
    while (file_list.last() == "") {
        file_list.pop_back();
    }
    index_file = file_list.last();
    index_file = "./index/" + index_file + ".db";
    QFile conf_file("./index/" + file_list.last() + ".txt");
    if (!conf_file.open(QFile::WriteOnly | QFile::Text | QFile::Truncate)) {
        QMessageBox::warning(this, "系统警告", "无法写入文件" + index_file + ".txt");
        return;
    }
    QTextStream ts(&conf_file);
    ts << this->ui->fold_line_edit->text();
    conf_file.close();
    this->ui->result_text_edit->setPlainText("正在计算文件量……");
    this->index_thread->dir = this->ui->fold_line_edit->text() + QDir::separator();
    this->index_thread->file_name = index_file;
    this->index_thread->is_all_index = this->add_index;
    this->ui->create_index->setText("索引中");
    this->ui->create_index->setEnabled(false);
    this->index_thread->start();
}

void MainWindow::on_fold_line_edit_textChanged(const QString &arg1)
{
    QDir target_dir(arg1);
    if (!target_dir.exists()) {
        this->ui->fold_line_edit->setEnabled(false);
        return;
    } else {
        this->ui->fold_line_edit->setEnabled(true);
    }
    QString index_file_name;
    QStringList file_list = arg1.split(QDir::separator());
    while (file_list.last() == "") {
        file_list.pop_back();
    }
    index_file_name = file_list.last();
    index_file_name = "./index/" + index_file_name + ".db";
    QFile index_file(index_file_name);
    if (index_file.exists()) {
        this->add_index = true;
        this->ui->create_index->setText("增量索引");
    } else {
        this->add_index = false;
        this->ui->create_index->setText("建立索引");
    }
}
